<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        v-permission="['sys:user:save']"
        v-waves
        style="margin-right: 153px; float: right"
        type="primary"
        icon="el-icon-plus"
        @click="create"
        >创建新设备类别</el-button
      >
      <el-upload
        style="margin-right: 33px; float: right"
        :action="uploadPath"
        :headers="headers"
        :on-success="handleExcelSuccess"
        :on-error="handleExcelError"
        :on-remove="handleRemoveExcel"
        :file-list="fileList"
        :limit="1"
        :show-file-list="false"
        :accept="accept"
      >
        <el-button type="primary"
          >批量导入</el-button
        >
        <div slot="tip" class="el-upload__tip"></div>
      </el-upload>
      <!-- <el-button
        v-permission="['sys:user:save']"
        v-waves
        style="margin-right: 33px; float: right"
        type="primary"
        icon="el-icon-upload2"
        @click="importBatchEquipment"
        >批量导入</el-button
      > -->
      <!-- <el-button
        v-permission="['sys:user:save']"
        v-waves
        style="margin-right: 33px; float: right"
        type="primary"
        icon="el-icon-download"
        @click="getImportBatchEquipmentFile"
        >获取批量导入格式</el-button
      > -->

      <!-- <el-link :href="tempPath" type="info" target="_blank">下载导入模板</el-link> -->
      <!-- <el-button
        v-permission="['sys:user:save']"
        v-waves
        style="margin-right: 153px; float: right"
        type="primary"
        icon="el-icon-plus"
        @click="test"
        >test</el-button
      > -->
    </div>

    <el-table
      :key="tableKey"
      :data="list"
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        label="类别id"
        prop="typeId"
        width="70px"
        align="center"
      />
      <el-table-column label="类别名称" prop="typeName" align="center" />

      <el-table-column label="操作" align="center" width="500px">
        <template slot-scope="{ row }">
          <el-button
            v-waves
            v-permission="['sys:role:list']"
            type="primary"
            @click="update(row.id)"
            >编辑</el-button
          >
          
          <el-button
            v-waves
            v-permission="['sys:role:save']"
            style="margin-left: 10px"
            type="primary"
            @click="openProductNode(row.id, row.typeName, row.typeId)"
            >下级</el-button
          >
          <el-button
            v-waves
            v-permission="['sys:role:save']"
            style="margin-left: 10px"
            type="primary"
            @click="remove(row.id)"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <!-- 以下是添加或者编辑弹窗 -->
    <el-dialog
      :title="addOrUpdate"
      :visible.sync="dialogCreateVisible"
      :close-on-click-modal="false"
      top="2vh"
      width="600px"
    >
      <el-form
        ref="dataForm"
        :model="newEequipment"
        :rules="rules"
        label-position="right"
        label-width="100px"
        style="width: 90%"
      >
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="newEequipment.name" placeholder="请输入类别名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-waves @click="dialogCreateVisible = false">取消</el-button>
        <el-button v-waves type="primary" @click="createEquipmentType()"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 以上是添加或者编辑弹窗 -->

    <!-- 以下是 产品信息节点框-->
    <el-dialog
      :title="equipmentProductInfoTitle"
      :visible.sync="dialogProductVisible"
      width="70%"
    >
      <div class="filter-container">
        <el-button
          v-permission="['sys:user:save']"
          v-waves
          style="margin-right: 285px; float: right; margin-top: -50px"
          type="primary"
          icon="el-icon-plus"
          @click="createNewProduct"
          >创建新设备</el-button
        >
      </div>
      <el-table :data="equipmentProductInfoList">
        <el-table-column
          property="typeId"
          label="产品id"
          width="150"
        ></el-table-column>
        <el-table-column
          property="typeName"
          label="产品名称"
          width="200"
        ></el-table-column>

        <el-table-column fixed="right" label="操作" width="500px">
          <template slot-scope="scope">
            <el-button
              v-waves
              style="margin-left: 10px"
              type="primary"
              @click="updateProduct(scope.row.id)"
              >编辑</el-button
            >

            <el-button
              v-waves
              style="margin-left: 10px"
              type="primary"
              @click="openModelNode(scope.row)"
              >下级</el-button
            >
            <el-button
              v-waves
              style="margin-left: 10px"
              type="primary"
              @click="removeProduct(scope.row.id)"
              >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 以上是 产品信息节点框-->

    <!-- 以下是产品信息的 添加或者编辑弹窗 -->
    <el-dialog
      :title="addOrUpdateProduct"
      :visible.sync="dialogProductCreateOrUpdateVisible"
      :close-on-click-modal="false"
      top="2vh"
      width="400px"
    >
      <el-form
        ref="dataFormProduct"
        :model="newEequipmentProduct"
        :rules="rules"
        label-position="right"
        label-width="100px"
        style="width: 90%"
      >
        <el-form-item label="产品名称" prop="name">
          <el-input
            v-model="newEequipmentProduct.name"
            placeholder="请输入产品名称"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-waves @click="dialogProductCreateOrUpdateVisible = false"
          >取消</el-button
        >
        <el-button v-waves type="primary" @click="createEquipmentProducte()"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 以上是产品信息的  添加或者编辑弹窗 -->

    <!-- 以下是 型号信息节点框-->
    <el-dialog
      :title="equipmentModelInfoTitle"
      :visible.sync="dialogModelVisible"
      width="70%"
    >
      <div class="filter-container">
        <el-button
          v-permission="['sys:user:save']"
          v-waves
          style="margin-right: 285px; float: right; margin-top: -50px"
          type="primary"
          icon="el-icon-plus"
          @click="createNewModel"
          >创建新型号</el-button
        >
      </div>
      <el-table :data="equipmentModelInfoList">
        <el-table-column
          property="typeId"
          label="型号id"
          width="150"
        ></el-table-column>
        <el-table-column
          property="typeName"
          label="型号名称"
          width="200"
        ></el-table-column>

        <el-table-column fixed="right" label="操作" width="500px">
          <template slot-scope="scope">
            <el-button
              v-waves
              style="margin-left: 10px"
              type="primary"
              @click="updateModel(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              v-waves
              style="margin-left: 10px"
              type="primary"
              @click="removeModel(scope.row.id)"
              >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 以上是 型号信息节点框-->

    <!-- 以下是型号信息的 添加或者编辑弹窗 -->
    <el-dialog
      :title="addOrUpdateModelTitle"
      :visible.sync="dialogModelCreateOrUpdateVisible"
      :close-on-click-modal="false"
      top="2vh"
      width="400px"
    >
      <el-form
        ref="dataFormModel"
        :model="newEequipmentModle"
        :rules="rules"
        label-position="right"
        label-width="100px"
        style="width: 90%"
      >
        <el-form-item label="型号名称" prop="name">
          <el-input
            v-model="newEequipmentModle.name"
            placeholder="请输入型号名称"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-waves @click="dialogModelCreateOrUpdateVisible = false"
          >取消</el-button
        >
        <el-button
          v-waves
          type="primary"
          @click="createOrUpdateEquipmentModel()"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 以上型号信息的  添加或者编辑弹窗 -->
  </div>
</template>

<script>
import {
  getList,
  createEquipmentType,
  remove,
  getEquipmentTypeOne,
  getProductInfoList,
  createOrUpdateEquipmentProduct,
  createOrUpdateEquipmentmodel,
  getImportBatchEquipmentFile,
  excelURL,
  test,
} from "@/api/equipment/equipment.js";
import { download, openFile } from "@/api/common/index.js";
import { getToken, getTokenName } from "@/utils/auth";
import waves from "@/directive/waves"; // Waves directive
// import Vue from 'vue'
import axios from "axios";
// import VueAxios from 'vue-axios'
export default {
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        orderByField: "createdAt",
        orderBy: "desc",
      },

      //以下是文件上传相关的参数
      //文件上传的路径
      uploadPath: "",
      headers: {},
      fileList: [],
      accept: "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", //限制文件类型

      //新设备
      newEequipment: {
        name: "",
        id: "",
      },
      addOrUpdate: "添加",
      params: {
        Authorization:
          "Bearer eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiIyYjMxZjc2ZTU3NjY0YWJmYWZjODNmYmVlM2E4NjUwNSIsImF1dGgiOiLns7vnu5_nrqHnkIblkZgiLCJzdWIiOiJhZG1pbiJ9.clWeT_lqcg7l6nnjc739kQHVGSv0xCAmm8x1qQ_0fJ9JFr8WHpDXdn3mvSQ0tfSzZs4Qhs5KgsZzyADOMmvewQ",
      },

      //设备产品信息列表
      equipmentProductInfoList: [],
      dialogProductVisible: false,
      equipmentProductInfoTitle: "",
      curequipmentId: "",

      //产品信息添加修改弹窗
      dialogProductCreateOrUpdateVisible: false,
      equipmentModelInfoList: [],
      dialogModelVisible: false,
      equipmentModelInfoTitle: "",
      curequipmentProductId: "",
      newEequipmentProduct: {
        name: "",
        id: "",
        parentId: "",
      },

      addOrUpdateProduct: "",

      //新型号对象
      newEequipmentModle: {
        name: "",
        id: "",
        parentId: "", //父级id
      },
      addOrUpdateModelTitle: "",
      dialogModelCreateOrUpdateVisible: false,

      rules: {
        name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (
                this.newEequipment.name == null ||
                value == null ||
                value.length == 0
              ) {
                callback("不能为空");
              } else if (value.length > 8) {
                callback("不能大于8个字"); //
              } else if (/[^\u4e00-\u9fa5]/.test(value)) {
                callback(new Error("必须是中文且不能有空格!"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },

      dialogCreateVisible: false,
      formLabelWidth: "120px",
    };
  },

  //页面初始化做的事情
  created() {
    this.getList();
    this.uploadPath = excelURL();
    this.headers[getTokenName()] = getToken();
  },
  methods: {
    //只是测试
    test() {
      test();
    },
    // 获取数据
    getList() {
      getList(this.listQuery).then((response) => {
        this.list = response.list;
        this.total = response.totalCount;
      });
    },

    //添加弹窗
    create() {
      this.dialogCreateVisible = true;
      this.addOrUpdate = "请填写:";
      this.newEequipment.name = "";
      this.newEequipment.id = "";
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    //修改弹窗
    update(id) {
      //添加或者修改之前 把前面的都清空
      getEquipmentTypeOne(id).then((response) => {
        this.dialogCreateVisible = true;
        this.newEequipment.name = response;
        this.newEequipment.id = id;
        this.addOrUpdate = "编辑";
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      });
    },

    /**
     * 打开产品节点
     */
    openProductNode(id, typeName, typeId) {
      //查询子节点,并且展示子节点
      getProductInfoList(id).then((response) => {
        //赋值
        this.equipmentProductInfoList = response;
        this.equipmentProductInfoTitle = typeName + "产品信息";
        this.dialogProductVisible = true;
        this.newEequipmentProduct.parentId = id; //当前设备的id 赋值
        this.newEequipmentProduct.parentTypeId = typeId;
        this.curequipmentId = id;
        //展示产品节点框
      });
    },

    //创建新的设备产品 按钮
    createNewProduct() {
      this.dialogProductCreateOrUpdateVisible = true;
      //添加新的设备
      this.addOrUpdateProduct = "请填写:";
      //清空原来的数据而已
      this.newEequipmentProduct.name = "";
      this.newEequipmentProduct.id = "";
      this.$nextTick(() => {
        this.$refs["dataFormProduct"].clearValidate();
      });
    },

    //创建或修改新产品的 确定按钮
    createEquipmentProducte() {
      this.$refs["dataFormProduct"].validate((valid) => {
        if (valid) {
          //发送Ajax 添加或者修改设备类型
          createOrUpdateEquipmentProduct(this.newEequipmentProduct).then(() => {
            //重新获取最新的 产品的列表
            this.dialogProductCreateOrUpdateVisible = false;
            getProductInfoList(this.curequipmentId).then((response) => {
              //赋值
              this.equipmentProductInfoList = response;
              //this.equipmentProductInfoTitle = typeName + "产品信息";
              this.dialogProductVisible = true;
              // this.newEequipmentProduct.parentId = id; //当前设备的id 赋值
              // this.newEequipmentProduct.parentTypeId = typeId;
              // this.curequipmentId = id;
              //展示产品节点框
            });
          });
        }
      });
    },

    //修改产品的弹窗......
    updateProduct(id) {
      //打开
      this.dialogProductCreateOrUpdateVisible = true;
      //添加新的设备
      this.addOrUpdateProduct = "请编辑:";
      getEquipmentTypeOne(id).then((response) => {
        this.newEequipmentProduct.name = response;
        this.newEequipmentProduct.id = id;
        //this.newEequipment.id = id;
        //this.addOrUpdate = "编辑";
        this.$nextTick(() => {
          this.$refs["dataFormProduct"].clearValidate();
        });
      });
    },

    //打开型号节点
    openModelNode(row) {
      //alert("id为:" + row.id + "名字为:" + row.typeName);
      //打开新的窗口
      getProductInfoList(row.id).then((response) => {
        //赋值
        this.equipmentModelInfoList = response;
        this.equipmentModelInfoTitle = row.typeName + "     型号信息";
        this.dialogModelVisible = true; //打开新窗口
        this.newEequipmentModle.parentId = row.id;
        this.newEequipmentModle.parentTypeId = row.typeId;
        this.curequipmentProductId = row.id;
        //展示产品节点框
      });
    },

    //点击修改型号按钮
    updateModel(id) {
      //打开修改或者创建的窗口
      this.dialogModelCreateOrUpdateVisible = true;
      //添加新的设备
      this.addOrUpdateModelTitle = "请编辑:";
      getEquipmentTypeOne(id).then((response) => {
        this.newEequipmentModle.name = response;
        this.newEequipmentModle.id = id;
        this.$nextTick(() => {
          this.$refs["dataFormModel"].clearValidate();
        });
      });
    },

    //点击创建新型号的按钮
    createNewModel() {
      //打开新建修改的弹窗   .各种赋值
      this.addOrUpdateModelTitle = "请添加:";
      this.dialogModelCreateOrUpdateVisible = true;
      this.newEequipmentModle.name = "";
      this.newEequipmentModle.id = "";
      this.$nextTick(() => {
        this.$refs["dataFormModel"].clearValidate();
      });
    },

    //添加或者修改型号信息的  确认按钮
    createOrUpdateEquipmentModel() {
      this.$refs["dataFormModel"].validate((valid) => {
        if (valid) {
          //发送Ajax 添加或者修改设备类型
          createOrUpdateEquipmentmodel(this.newEequipmentModle).then(
            (response) => {
              //重新获取最新的 产品的列表
              this.dialogModelCreateOrUpdateVisible = false;
              getProductInfoList(this.curequipmentProductId).then(
                (response) => {
                  //赋值
                  this.equipmentModelInfoList = response;
                  //this.equipmentProductInfoTitle = typeName + "产品信息";
                  this.dialogProductVisible = true;
                }
              );
            }
          );
        }
      });
    },

    //移除某个型号
    removeModel(id) {
      this.$confirm("此操作将永久删除该型号, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        remove(id).then((response) => {
          if (response == 1) {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000,
            });
          } else {
            //按道理说不可能到这里的
            this.$notify({
              title: "失败",
              message: "删除失败,该型号已被使用",
              type: "error",
              duration: 2000,
            });
          }

          this.dialogModelCreateOrUpdateVisible = false;
          getProductInfoList(this.curequipmentProductId).then((response) => {
            //赋值
            this.equipmentModelInfoList = response;
          });
        });
      });
    },

    //移除某个产品
    removeProduct(id) {
      this.$confirm("此操作将永久删除该类别, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        remove(id).then((response) => {
          if (response == 1) {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000,
            });
          } else {
            this.$notify({
              title: "失败",
              message: "删除失败,该产品已被使用",
              type: "error",
              duration: 2000,
            });
          }

          this.dialogProductCreateOrUpdateVisible = false;
          getProductInfoList(this.curequipmentId).then((response) => {
            //赋值
            this.equipmentProductInfoList = response;
          });
        });
      });
    },

    //移除类别
    remove(id) {
      this.$confirm("此操作将永久删除该类别, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        remove(id).then((response) => {
          if (response == 1) {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000,
            });
          } else {
            this.$notify({
              title: "失败",
              message: "删除失败,该类别已被使用",
              type: "error",
              duration: 2000,
            });
          }

          this.getList();
        });
      });
    },

    //添加或者修改设备类型
    createEquipmentType() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          //发送Ajax 添加或者修改设备类型
          createEquipmentType(this.newEequipment).then(() => {
            this.dialogCreateVisible = false;
            this.newEequipment.name = "";
            this.getList();
          });
        }
      });
    },

    handleExcelError() {
      this.fileList = [];
    },
    handleExcelSuccess(response, file, fileList) {
    
      if (response.code !== 0) {
        this.$message.error(response.msg);
      } else {
        this.getList();
       
      }
    },
    handleRemoveExcel(file, fileList) {},

    //批量导入
    importBatchEquipment() {
      alert("批量导入");
    },

    //     axiosUpload(parmas, ajaxUrl).then((res) => {
    //     //res 为文档流
    //     if (res) {
    //         let url = window.URL.createObjectURL(new Blob([res], { type: 'application/vnd.ms-excel' })) //处理文档流
    //         let link = document.createElement('a')
    //         link.style.display = 'none'
    //         link.href = url
    //         link.download = fileName
    //         document.body.appendChild(link)
    //         link.click()
    //     } else {
    //         message.error('暂无数据，无法导出！')
    //     }
    // })

    //获取批量导入的 格式文件
    getImportBatchEquipmentFile() {
      var parms = this.params;
      axios({
        method: "GET",
        url: "http://192.168.1.38:8081/common/open_file20210408000014",
        params: parms,
        responseType: "blob",
      })
        .then((res) => {
          console.log("以下是返回的数据");
          console.log(res);
          console.log("以上是返回的数据");
          let blob = new Blob([res.data], {
            type:
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          });
          let url = window.URL.createObjectURL(blob);
          window.location.href = url;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    handleExport() {
      const headers = {};
      headers[getTokenName()] = getToken();
      API.exportExcel(headers).then((res) => {
        if (res.data.type === "application/json") {
          this.$message({
            type: "error",
            message: "下载失败，文件不存在或权限不足",
          });
        } else {
          const blob = new Blob([res.data]);
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, "用法用量模板.xlsx");
          } else {
            const link = document.createElement("a");
            const evt = document.createEvent("HTMLEvents");
            evt.initEvent("click", false, false);
            link.href = URL.createObjectURL(blob);
            link.download = "用法用量模板.xlsx";
            link.style.display = "none";
            document.body.appendChild(link);
            link.click();
            window.URL.revokeObjectURL(link.href);
          }
        }
      });
    },

    handleFilter() {
      this.listQuery.pageNo = 1;
      this.getList();
    },
  },
};
</script>
